package com.csun.cmny.provider.netty.test;

import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: chisj chisj@foxmal.com
 * @Date: 2019-10-15 10:02
 * @Description:
 */
@Slf4j
@Component
public class TcpMessageHandler {

    private ConcurrentHashMap<String, Channel> clientMap = new ConcurrentHashMap<>();

    /**
     *
     * @param ctx
     * @param data
     */
    public void handler(ChannelHandlerContext ctx, String data) {

        try {
            Map map = JSONObject.fromObject(data);
            String msgType = (String) map.get("msgType");
            if (msgType == null) {
                log.warn("未识别的消息...{}", data);
            }
            switch (msgType) {
                case "login" :
                    String client = (String) map.get("client");
                    clientMap.put(client, ctx.channel());
                    break;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ;
        }
    }

    public void send(String client, String message) {

        // 判断设备是否在线
        Channel channel = clientMap.get(client);
        if (channel == null) {
            throw new RuntimeException("设备尚未接入.");
        }

        if (!channel.isActive()) {
            throw new RuntimeException("设备不在线.");
        }

        // 发送数据
        channel.writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));

    }
}
